<!-- 角色信息 -->
<!-- 角色信息 -->
<template>
  <div>
    <el-dialog v-model="dialogVisible" width="400" title="设置" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
      <el-form ref="elFormRef" :model="formData" :rules="rules" scrollToError statusIcon>
        <el-form-item label="设置支付提成比例" labelWidth="12em" prop="thatDayLimitRate">
          <base-input-number
            v-model="formData.thatDayLimitRate"
            :decimals="2"
            :min="thatDayLimitRateMin"
            :max="thatDayLimitRateMax"
            verify="add_int"
            placeholder="请输入支付提成比例"
            clearable
          ></base-input-number>
        </el-form-item>
        <el-form-item labelWidth="12em" label="合作方最终显示总收益" prop="showTotalMoney">
          <el-input :modelValue="showTotalMoney" disabled></el-input>
        </el-form-item>
        <el-form-item labelWidth="12em" label="是否强制修改显示金额" prop="force">
          <el-switch v-model="force"></el-switch>
        </el-form-item>
        <div ref="parent">
          <el-form-item v-if="force" labelWidth="12em" label="强制修改显示金额" prop="virtualThatDayAmount">
            <base-input-number
              v-model="formData.virtualThatDayAmount"
              :decimals="2"
              verify="add_float"
              placeholder="请输入显示金额"
              clearable
            ></base-input-number>
          </el-form-item>
        </div>
        <el-form-item labelWidth="0em">
          <div style="width: 100%; padding-top: 20px">
            <el-button style="width: 100%" type="success" :loading="submitLoading" :disabled="submitLoading" :icon="IconPlus" @click="submit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import IconPlus from '~icons/ep/plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import { type CooperationDrama, type SettingCooperationInfoRequest, settingCooperationInfoAxios } from '@/api/cooperation-management';
  import { useAutoAnimate } from '@formkit/auto-animate/vue';
  type $ShowData = {
    cooperationDrama: CooperationDrama;
    /** 设置完成后的回调 */
    settingCallBack?: () => void;
  };
  let settingCallBack: $ShowData['settingCallBack'] = undefined;
  const submitLoading = ref(false);
  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);

  const formData: SettingCooperationInfoRequest = reactive<SettingCooperationInfoRequest>({
    incomeId: null,
    virtualThatDayAmount: null,
    thatDayLimitRate: 80,
  });
  const [parent] = useAutoAnimate();
  const totalAmount = ref(0);
  const force = ref(false);
  const showTotalMoney = computed(() => {
    if (typeof formData.virtualThatDayAmount === 'number') {
      return Math.round(formData.virtualThatDayAmount * 100) / 100;
    } else {
      const rate = typeof formData.thatDayLimitRate === 'number' ? formData.thatDayLimitRate! / 100 : 1;
      return Math.round(rate * totalAmount.value * 100) / 100;
    }
  });
  watch(
    () => force.value,
    () => {
      formData.virtualThatDayAmount = null;
    }
  );

  const thatDayLimitRateMin = 1;
  const thatDayLimitRateMax = 100;
  const rules: FormRules = {
    virtualThatDayAmount: [{ type: 'number', message: '设置当日收入金额不合法', trigger: ['blur', 'change'] }],
    thatDayLimitRate: [
      { required: true, type: 'number', message: '请输入支付提成比例', trigger: ['blur', 'change'] },
      {
        min: thatDayLimitRateMin,
        max: thatDayLimitRateMax,
        type: 'number',
        message: `支付提成比例只能输入${thatDayLimitRateMin}-${thatDayLimitRateMax}`,
        trigger: ['blur', 'change'],
      },
    ],
  };

  /**
   * 显示
   */
  function show(data: $ShowData) {
    const { thatDayLimitRate, virtualThatDayAmount, incomeId } = data.cooperationDrama;
    formData.incomeId = incomeId;
    formData.thatDayLimitRate = (typeof thatDayLimitRate === 'number' ? thatDayLimitRate : 0.8) * 100;
    totalAmount.value = data.cooperationDrama.totalAmount;
    force.value = typeof virtualThatDayAmount === 'number';
    // 一定要在  force.value 赋值后，因为force.value有监听
    formData.virtualThatDayAmount = typeof virtualThatDayAmount === 'number' ? virtualThatDayAmount : null;
    settingCallBack = 'settingCallBack' in data && typeof data.settingCallBack === 'function' ? data.settingCallBack : undefined;
    dialogVisible.value = true;
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  /** 提交 */
  async function submit() {
    try {
      await elFormRef.value?.validate();
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
      return;
    }
    try {
      submitLoading.value = true;
      await settingCooperationInfoAxios(formData);
      typeof settingCallBack === 'function' && settingCallBack();
      ElToast.success('操作成功');
      hide();
      submitLoading.value = false;
    } catch (error) {
      submitLoading.value = false;
      ElToast.error(error.msg || '提交失败，-BD003');
    }
  }

  defineExpose({ show, hide });
</script>
